package com.zeng.stpro.commons.exception;

import com.zeng.stpro.commons.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @Author ZENGZHIJUN
 * @Date 2021/2/2 15:45
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 捕获IP 无权限异常
     */
    @ExceptionHandler(IpNotAllowedException.class)
    public R handleIpNotAllowedException(IpNotAllowedException e) {
        if (e instanceof IpNotAllowedException) {
            return R.ng(e.getMsg(), e.getCode());
        }
        return R.ng();
    }

    /**
     *捕获业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(StrawberryException.class)
    public R handleStrawberryException(StrawberryException e) {
        return R.ng(e.getMsg(), e.getCode());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public R handleNoFoundException(Exception e) {
        logger.error(e.getMessage(), e);
        return R.ng("路径不存在", HttpStatus.NOT_FOUND.value());
    }


    /**
     * 所有其它的异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return R.ng();
    }

}
